﻿//Create by daniel @ 2012.8.24
//change log:
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YunCMS.Common;
using System.Web;

namespace YunCMS.Core.Configration
{
    public class Config
    {
        public XmlControl XmlFile { get; set; }


        protected virtual string RootNode { 
            get { return "/siteconfig"; } 
        }

        public Config() { }

        /// <summary>
        /// virual path of xmlfile.
        /// </summary>
        /// <param name="xmlPath"></param>
        public Config(string xmlPath)
        {
            XmlFile = LoadXml(xmlPath);
        }

        public Config(string xmlPath, string cacheKey)
        {
            XmlFile = LoadXml(xmlPath, cacheKey);
        }

        /// <summary>
        /// Load xmlControl from file.
        /// </summary>
        /// <param name="xmlPath"></param>
        /// <returns></returns>
        protected XmlControl LoadXml(string xmlPath)
        {
            string path = IOUtil.GetMapPath(xmlPath);
            return new XmlControl(path);
        }

        /// <summary>
        /// Load xmlControl from cache (if file doesn't change)
        /// </summary>
        protected XmlControl LoadXml(string xmlPath, string cacheKey)
        {
            string path = IOUtil.GetMapPath(xmlPath);

            XmlControl xmlControl = CacheUtil.Get<XmlControl>(cacheKey);
            if (xmlControl == null)
            {
                CacheUtil.Insert(cacheKey, new XmlControl(path), path);
                xmlControl = CacheUtil.Get<XmlControl>(cacheKey);
            }

            return xmlControl;
        }


        protected virtual string GetText(string path)
        {
            return XmlFile.GetText(path);
        }

        protected virtual void SetText(string path, string value)
        {
            if (!XmlFile.ExistNode(path))
            {
                string name = path.Substring(path.LastIndexOf('/') + 1);
                XmlFile.InsertElement(RootNode, name, value);
                return;
            }
            XmlFile.Replace(path, value);
        }

        public virtual void Save()
        {
            XmlFile.Save();
        }
    }
}
